package example.atestEntity;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Down {
    public static ResponseEntity<byte[]> downloadFolder() {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

            File folder = new File("C:\\haha\\2023年10月19日");
            addToZip(folder, folder.getName(), zipOutputStream);

            zipOutputStream.close();
            byteArrayOutputStream.close();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "1");
            headers.setContentLength(byteArrayOutputStream.size());

            return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常情况
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private static void addToZip(File file, String fileName, ZipOutputStream zipOutputStream) throws IOException {
        if (file.isDirectory()) {
            if (fileName.endsWith("/")) {
                zipOutputStream.putNextEntry(new ZipEntry(fileName));
            } else {
                zipOutputStream.putNextEntry(new ZipEntry(fileName + "/"));
            }

            zipOutputStream.closeEntry();

            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    addToZip(child, fileName + "/" + child.getName(), zipOutputStream);
                }
            }
        } else {
            FileInputStream fileInputStream = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fileInputStream.read(bytes)) >= 0) {
                zipOutputStream.write(bytes, 0, length);
            }

            fileInputStream.close();
            zipOutputStream.closeEntry();
        }
    }
}